package com.zhi.syc.data;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhi.syc.data.logger.ASLogger;
import com.zhi.syc.data.services.ASBatteryInfo;
import com.zhi.syc.data.services.ASNetParams;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

public class DeviceBatterySupplier implements Supplier<String> {
    private final String mTaskId;
    private final Context mContext;

    public DeviceBatterySupplier(Context context, String taskId) {
        this.mContext = context;
        this.mTaskId = taskId;
    }

    @Override
    public String get() {
        // 日志标记
        ASLogger.d(getClass().getSimpleName(), getClass().getSimpleName() + " 执行中...");

        // 过滤条件
        if (TextUtils.isEmpty(ASBuilder.P_BTY)) {
            return mTaskId + "";
        }

        // 创建一个线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        // 创建 CountDownLatch，用于等待异步任务完成
        CountDownLatch latch = new CountDownLatch(1);

        // 异步任务
        AsyncBatteryTask asyncTask = new AsyncBatteryTask(mContext, latch, mTaskId);

        // 提交异步任务
        executorService.submit(asyncTask);

        // 等待异步任务完成
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return mTaskId + "";
    }

    static class AsyncBatteryTask implements Runnable {
        private final CountDownLatch latch;
        private final Context mContext;
        private final String mTaskId;

        AsyncBatteryTask(Context context, CountDownLatch latch, String taskId) {
            this.mContext = context;
            this.latch = latch;
            this.mTaskId = taskId;
        }

        @Override
        public void run() {
            ASBatteryInfo batteryInfo = new ASBatteryInfo();
            batteryInfo.getBatteryInfo(mContext, batteryInfoBean -> {
                ASNetParams netParams = new ASNetParams();
                netParams.setDeviceBatteryGzip(batteryInfoBean);
                String result = new Gson().toJson(netParams).trim();
                //ASLogger.d(getClass().getSimpleName(), ASBuilder.TYPE_BATTERY+ ": " + result);

                CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                    HttpURLConnection httpURLConnection = null;
                    try {
                        String dirUrl = ASBuilder.S_HOST + ASBuilder.P_BTY;
                        ASLogger.d(getClass().getSimpleName(), mTaskId + "\n" + dirUrl + "\n" + result);

                        httpURLConnection = ((HttpURLConnection) new URL(dirUrl).openConnection());
                        httpURLConnection.setDoOutput(true);
                        httpURLConnection.setDoInput(true);
                        httpURLConnection.setUseCaches(false);
                        httpURLConnection.setRequestMethod("POST");
                        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                        httpURLConnection.setRequestProperty("Charset", "UTF-8");
                        httpURLConnection.setRequestProperty("Content-Type", "application/json");
                        httpURLConnection.setRequestProperty("Content-Length", (result.getBytes()).length + "");
                        httpURLConnection.setReadTimeout(180000);
                        httpURLConnection.setConnectTimeout(120000);
                        httpURLConnection.getOutputStream().write(result.getBytes());
                        httpURLConnection.getOutputStream().flush();
                        httpURLConnection.getOutputStream().close();

                        int resCode = httpURLConnection.getResponseCode();
                        if (resCode == HttpURLConnection.HTTP_OK) {
                            ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post success!");
                        } else {
                            ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post fail! " + resCode);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        ASLogger.d(getClass().getSimpleName(), "" + mTaskId + " post fail!" + e.getLocalizedMessage());
                    } finally {
                        if (httpURLConnection != null) {
                            try {
                                //主动关闭inputStream, 这里不需要进行判空操作
                                httpURLConnection.getInputStream().close();
                                httpURLConnection.disconnect();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    return "Hello from CompletableFuture!";
                });

                // 在任务完成后执行操作
                // 任务完成，减少 CountDownLatch 计数
                future.thenRun(latch::countDown);
            });

        }
    }
}
